using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace AdmissionQA.Application.Common;

public interface IDeepSeekService
{
    IAsyncEnumerable<string> StreamChatAsync(string query, string context, CancellationToken cancellationToken = default);
    Task<string> GetChatResponseAsync(string query, string context, CancellationToken cancellationToken = default);
}

public class DeepSeekService : IDeepSeekService
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<DeepSeekService> _logger;
    private readonly string _apiKey;
    private readonly string _apiUrl;

    public DeepSeekService(HttpClient httpClient, IConfiguration configuration, ILogger<DeepSeekService> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
        _apiKey = configuration["DeepSeek:ApiKey"] ?? throw new InvalidOperationException("DeepSeek API Key not configured");
        _apiUrl = configuration["DeepSeek:ApiUrl"] ?? "https://api.deepseek.com/v1/chat/completions";

        // 只添加Authorization头部，Content-Type应该在HttpContent中设置
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
    }

    public async IAsyncEnumerable<string> StreamChatAsync(string query, string context, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        var requestBody = new
        {
            model = "deepseek-chat",
            messages = new[]
            {
                new { role = "system", content = "你是一个智能招生问答助手，基于以下信息回答用户问题：" },
                new { role = "user", content = $"背景信息：{context}\n\n用户问题：{query}" }
            },
            stream = true,
            temperature = 0.7,
            max_tokens = 2000
        };

        var jsonContent = JsonSerializer.Serialize(requestBody);
        var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

        var response = await _httpClient.PostAsync(_apiUrl, content, cancellationToken);
        if (!response.IsSuccessStatusCode)
        {
            yield return "抱歉，AI服务暂时不可用，请稍后重试。";
            yield break;
        }

        using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
        using var reader = new StreamReader(stream);

        while (!reader.EndOfStream && !cancellationToken.IsCancellationRequested)
        {
            var line = await reader.ReadLineAsync();
            if (string.IsNullOrEmpty(line)) continue;

            if (line.StartsWith("data: "))
            {
                var data = line.Substring(6);
                if (data == "[DONE]") break;

                string? contentToYield = null;
                try
                {
                    var streamResponse = JsonSerializer.Deserialize<DeepSeekStreamResponse>(data);
                    var firstChoice = streamResponse?.Choices?.FirstOrDefault();
                    if (firstChoice?.Delta?.Content != null)
                    {
                        contentToYield = firstChoice.Delta.Content;
                    }
                }
                catch (JsonException ex)
                {
                    _logger.LogWarning(ex, "Failed to parse DeepSeek stream response: {Data}", data);
                }

                if (contentToYield != null)
                {
                    yield return contentToYield;
                }
            }
        }
    }

    public async Task<string> GetChatResponseAsync(string query, string context, CancellationToken cancellationToken = default)
    {
        var requestBody = new
        {
            model = "deepseek-chat",
            messages = new[]
            {
                new { role = "system", content = "你是一个智能招生问答助手，基于以下信息回答用户问题：" },
                new { role = "user", content = $"背景信息：{context}\n\n用户问题：{query}" }
            },
            stream = false,
            temperature = 0.7,
            max_tokens = 2000
        };

        var jsonContent = JsonSerializer.Serialize(requestBody);
        var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

        try
        {
            var response = await _httpClient.PostAsync(_apiUrl, content, cancellationToken);
            response.EnsureSuccessStatusCode();

            var responseContent = await response.Content.ReadAsStringAsync(cancellationToken);
            var deepSeekResponse = JsonSerializer.Deserialize<DeepSeekResponse>(responseContent);

            return deepSeekResponse?.Choices?.FirstOrDefault()?.Message?.Content ?? "抱歉，无法获取AI回答。";
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting response from DeepSeek API");
            return "抱歉，AI服务暂时不可用，请稍后重试。";
        }
    }
}

// DeepSeek API 响应模型
public class DeepSeekResponse
{
    [JsonPropertyName("choices")]
    public List<DeepSeekChoice>? Choices { get; set; }
}

public class DeepSeekChoice
{
    [JsonPropertyName("message")]
    public DeepSeekMessage? Message { get; set; }
}

public class DeepSeekMessage
{
    [JsonPropertyName("content")]
    public string? Content { get; set; }
}

// DeepSeek 流式响应模型
public class DeepSeekStreamResponse
{
    [JsonPropertyName("choices")]
    public List<DeepSeekStreamChoice>? Choices { get; set; }
}

public class DeepSeekStreamChoice
{
    [JsonPropertyName("delta")]
    public DeepSeekDelta? Delta { get; set; }
}

public class DeepSeekDelta
{
    [JsonPropertyName("content")]
    public string? Content { get; set; }
}